package org.arch_learn.io.bio;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class SocketServer {
    public static void main(String[] args) throws IOException {
        //1.创建线程池，如果有一个客户端连接就创建线程与之通信
        ExecutorService executorService = Executors.newCachedThreadPool();
        //2.创建ServerSocket对象
        ServerSocket serverSocket = new ServerSocket(9999);
        System.out.println("服务器已启动!");
        //3.阻塞线程监听客户端
        while (true) {
            Socket socket = serverSocket.accept();
            executorService.execute(() -> {
                try {
                    handle(socket);
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    //6.关闭连接
                    try {
                        socket.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }

    private static void handle(Socket socket) throws IOException {
        Thread thread = Thread.currentThread();
        System.out.println("id为:" + thread.getId() + "名称为:" + thread.getName() + "的线程正在处理客户端请求...");
        //4.获取输入内容
        InputStream inputStream = socket.getInputStream();
        byte[] bytes = new byte[1024];
        int read = inputStream.read(bytes);
        System.out.println("客户端请求内容：" + new String(bytes, 0, read));
        //5.获取输出流，输出内容
        OutputStream outputStream = socket.getOutputStream();
        outputStream.write("response".getBytes());
    }
}
